<template>
  <div class="my-job-applications">
    <el-card>
      

      <!-- 搜索表单 -->
      <div class="search-form">
        <div class="search-form-header">
          <h3 class="search-title">
            <el-icon><Search /></el-icon>
            筛选条件
          </h3>
          <el-button
            text
            type="primary"
            @click="toggleSearchForm"
            class="toggle-btn"
          >
            {{ searchFormCollapsed ? '展开' : '收起' }}
            <el-icon class="toggle-icon" :class="{ 'is-collapsed': searchFormCollapsed }">
              <ArrowDown />
            </el-icon>
          </el-button>
        </div>

        <el-collapse-transition>
          <div v-show="!searchFormCollapsed" class="search-form-content">
            <el-form :model="searchForm" inline class="search-form-inner">
              <el-row :gutter="16">
                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="关键词搜索">
                    <el-input
                      v-model="searchForm.search"
                      placeholder="请输入公司名称、岗位名称"
                      clearable
                      prefix-icon="Search"
                      @keyup.enter="handleSearch"
                      class="search-input"
                    />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="申请状态">
                    <el-select
                      v-model="searchForm.status"
                      placeholder="请选择状态"
                      clearable
                      class="search-select"
                    >
                      <el-option label="待审核" value="pending" />
                      <el-option label="已通过" value="approved" />
                      <el-option label="已拒绝" value="rejected" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item label="申请时间">
                    <el-date-picker
                      v-model="searchForm.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      clearable
                      class="search-date-picker"
                    />
                  </el-form-item>
                </el-col>

                <el-col :xs="24" :sm="12" :md="8" :lg="6">
                  <el-form-item class="search-actions">
                    <el-button type="primary" @click="handleSearch" :loading="loading">
                      <el-icon><Search /></el-icon>
                      搜索
                    </el-button>
                    <el-button @click="handleReset">
                      <el-icon><RefreshLeft /></el-icon>
                      重置
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-transition>
      </div>

      <!-- 申请列表 -->
      <div class="application-list">
        <el-table
          :data="filteredApplicationList"
          v-loading="loading"
          stripe
          style="width: 100%"
          size="small"
        >
          <el-table-column label="岗位名称" min-width="150">
            <template #default="{ row }">
              {{ row.job_info?.title || '未知岗位' }}
            </template>
          </el-table-column>
          <el-table-column label="公司名称" min-width="150">
            <template #default="{ row }">
              {{ row.job_info?.company_info?.name || '未知公司' }}
            </template>
          </el-table-column>
          <el-table-column label="工作地点" min-width="120">
            <template #default="{ row }">
              {{ row.job_info?.work_location || '未知地点' }}
            </template>
          </el-table-column>
          <el-table-column label="薪资水平" width="120">
            <template #default="{ row }">
              {{ row.job_info?.salary_range || '面议' }}
            </template>
          </el-table-column>
          <el-table-column label="申请状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="申请时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="handleDetail(row)">查看详情</el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleSubmitResume(row)"
                v-if="row.status === 'approved'"
              >
                投递简历
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 申请详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="申请详情"
      width="800px"
    >
      <div class="application-detail" v-if="selectedApplication">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="岗位名称">
            {{ selectedApplication.job_info?.title || '未知岗位' }}
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            {{ selectedApplication.job_info?.company_info?.name || '未知公司' }}
          </el-descriptions-item>
          <el-descriptions-item label="工作地点">
            {{ selectedApplication.job_info?.work_location || '未知地点' }}
          </el-descriptions-item>
          <el-descriptions-item label="薪资水平">
            {{ selectedApplication.job_info?.salary_range || '面议' }}
          </el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusTagType(selectedApplication.status)">
              {{ getStatusText(selectedApplication.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDate(selectedApplication.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="联系邮箱" span="2">
            {{ selectedApplication.job_info?.company_info?.contact_email || '未提供' }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话" span="2" v-if="selectedApplication.job_info?.company_info?.contact_phone">
            {{ selectedApplication.job_info?.company_info?.contact_phone }}
          </el-descriptions-item>
          <el-descriptions-item label="公司地址" span="2">
            {{ selectedApplication.job_info?.company_info?.address || '未提供' }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="cover-letter" v-if="selectedApplication.cover_letter">
          <h4>求职信</h4>
          <p>{{ selectedApplication.cover_letter }}</p>
        </div>

        <div class="review-comments" v-if="selectedApplication.review_comments">
          <h4>审核意见</h4>
          <p>{{ selectedApplication.review_comments }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 投递简历对话框 -->
    <el-dialog
      v-model="submitDialogVisible"
      title="投递简历"
      width="500px"
    >
      <div class="submit-resume-content">
        <el-alert
          title="恭喜！您的岗位申请已通过审核"
          type="success"
          :closable="false"
          show-icon
          style="margin-bottom: 20px"
        />

        <div class="job-contact-info" v-if="selectedApplication">
          <h4>联系方式</h4>
          <p><strong>投递邮箱：</strong>{{ selectedApplication.job_info?.company_info?.contact_email || '未提供' }}</p>
          <p v-if="selectedApplication.job_info?.company_info?.contact_phone">
            <strong>联系电话：</strong>{{ selectedApplication.job_info?.company_info?.contact_phone }}
          </p>
          <p><strong>公司地址：</strong>{{ selectedApplication.job_info?.company_info?.address || '未提供' }}</p>
        </div>

        <el-alert
          title="请将您的简历发送至上述邮箱，或直接联系HR"
          type="info"
          :closable="false"
          style="margin-top: 20px"
        />
      </div>
      <template #footer>
        <el-button type="primary" @click="submitDialogVisible = false">
          我知道了
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, ArrowDown, RefreshLeft } from '@element-plus/icons-vue'
import { jobApplicationApi } from '@/api/jobs'
import type { JobApplication } from '@/types'

// 响应式数据
const loading = ref(false)
const applicationList = ref<JobApplication[]>([])
const selectedApplication = ref<JobApplication | null>(null)
const detailDialogVisible = ref(false)
const submitDialogVisible = ref(false)
const searchFormCollapsed = ref(false)

// 搜索表单
const searchForm = reactive({
  search: '',
  status: '',
  dateRange: [] as string[]
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 过滤后的申请列表 - 实现实时搜索
const filteredApplicationList = computed(() => {
  if (!applicationList.value.length) return []

  return applicationList.value.filter(application => {
    // 关键词搜索
    if (searchForm.search) {
      const searchText = searchForm.search.toLowerCase()
      const titleMatch = application.job_info?.title?.toLowerCase().includes(searchText)
      const companyMatch = application.job_info?.company_info?.name?.toLowerCase().includes(searchText)
      if (!titleMatch && !companyMatch) return false
    }

    // 申请状态筛选
    if (searchForm.status && application.status !== searchForm.status) {
      return false
    }

    // 日期范围筛选
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      const applicationDate = new Date(application.created_at)
      const startDate = new Date(searchForm.dateRange[0])
      const endDate = new Date(searchForm.dateRange[1])
      endDate.setHours(23, 59, 59, 999) // 设置为当天结束时间

      if (applicationDate < startDate || applicationDate > endDate) {
        return false
      }
    }

    return true
  })
})

// 方法
const toggleSearchForm = () => {
  searchFormCollapsed.value = !searchFormCollapsed.value
}

const fetchApplicationList = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.pageSize,
      search: searchForm.search,
      status: searchForm.status
    }

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.start_date = searchForm.dateRange[0]
      params.end_date = searchForm.dateRange[1]
    }

    const response = await jobApplicationApi.getApplicationList(params)
    applicationList.value = response.data.results || []
    pagination.total = response.data.count || 0
  } catch (error) {
    console.error('获取申请列表失败:', error)
    ElMessage.error('获取申请列表失败')
    applicationList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchApplicationList()
}

const handleReset = () => {
  searchForm.search = ''
  searchForm.status = ''
  searchForm.dateRange = []
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchApplicationList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchApplicationList()
}

const handleDetail = (application: JobApplication) => {
  selectedApplication.value = application
  detailDialogVisible.value = true
}

const handleSubmitResume = (application: JobApplication) => {
  selectedApplication.value = application
  submitDialogVisible.value = true
}

// 辅助方法
const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return map[status] || status
}

const getStatusTagType = (status: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  const map: Record<string, 'primary' | 'success' | 'warning' | 'info' | 'danger'> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  fetchApplicationList()
})
</script>

<style lang="scss" scoped>
.my-job-applications {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .search-form {
    margin-bottom: 12px;
    background: var(--bg-color-light);
    border: 1px solid var(--border-color-light);
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;

    .search-form-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 16px;
      background: var(--fill-color-light);
      border-bottom: 1px solid var(--border-color-extra-light);

      .search-title {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-color-primary);
        display: flex;
        align-items: center;
        gap: 6px;

        .el-icon {
          color: var(--color-primary);
          font-size: 16px;
        }
      }

      .toggle-btn {
        display: flex;
        align-items: center;
        gap: 4px;
        color: var(--text-color-regular);
        font-size: 12px;
        padding: 4px 8px;

        .toggle-icon {
          transition: transform 0.3s ease;
          font-size: 12px;

          &.is-collapsed {
            transform: rotate(-90deg);
          }
        }
      }
    }

    .search-form-content {
      padding: 12px 16px;
    }

    .search-form-inner {
      .el-form-item {
        margin-bottom: 8px;

        :deep(.el-form-item__label) {
          color: var(--text-color-regular);
          font-weight: 500;
          font-size: 12px;
          line-height: 1.2;
          margin-bottom: 4px;
        }
      }

      .search-input,
      .search-select,
      .search-date-picker {
        :deep(.el-input) {
          --el-input-height: 28px;
        }

        :deep(.el-select) {
          --el-select-input-height: 28px;
        }

        :deep(.el-date-editor) {
          --el-date-editor-height: 28px;
        }
      }

      .search-actions {
        display: flex;
        gap: 8px;
        align-items: flex-end;

        .el-button {
          height: 28px;
          padding: 0 12px;
          font-size: 12px;
        }
      }
    }
  }

  .application-list {
    :deep(.el-table) {
      --el-table-row-height: 40px;
      --el-table-header-height: 36px;
      font-size: 13px;

      .el-table__header-wrapper {
        .el-table__header {
          th {
            padding: 6px 0;
            background: var(--fill-color-light);
          }
        }
      }

      .el-table__body-wrapper {
        .el-table__body {
          td {
            padding: 6px 0;
          }
        }
      }

      .el-button {
        height: 24px;
        padding: 0 8px;
        font-size: 12px;

        &.el-button--small {
          height: 24px;
          padding: 0 8px;
        }
      }

      .el-tag {
        height: 20px;
        line-height: 18px;
        font-size: 11px;
        padding: 0 6px;
      }
    }

    .pagination-wrapper {
      margin-top: 12px;
      display: flex;
      justify-content: center;

      :deep(.el-pagination) {
        --el-pagination-button-height: 28px;
        --el-pagination-button-width: 28px;
        font-size: 12px;

        .el-pagination__sizes {
          .el-select {
            --el-select-input-height: 28px;
          }
        }

        .el-pagination__jump {
          .el-input {
            --el-input-height: 28px;
          }
        }
      }
    }
  }

  .application-detail {
    .cover-letter,
    .review-comments {
      margin-top: 20px;

      h4 {
        margin: 0 0 10px 0;
        color: #303133;
        font-size: 16px;
      }

      p {
        margin: 0;
        color: #606266;
        line-height: 1.6;
        padding: 12px;
        background-color: #f8f9fa;
        border-radius: 4px;
      }
    }
  }

  .submit-resume-content {
    .job-contact-info {
      margin: 20px 0;

      h4 {
        margin: 0 0 12px 0;
        color: #303133;
        font-size: 16px;
      }

      p {
        margin: 8px 0;
        color: #606266;

        strong {
          color: #303133;
        }
      }
    }
  }
}
</style>